// 加载文档
function load_doc(url, wd, without_history) {
    NProgress.start();
    $.get(url + "?fr=docaphptop", function (ret) {
        if (ret.status === 1) {
            GV.doc_id = ret.data.id; // 文档ID
            GV.book_id = ret.data.book_id; // 书籍ID
            let title = ret.data.title;
            let book_title = ret.data.book_title;
            $('#book-title').text(book_title);
            $('#book-title').attr('href', $('#book-title').attr('data-href')+'?id='+ ret.data.book_start_id);
            $('.book-ver').text(ret.data.book_ver);
            $("input[name=book_id]").val(GV.book_id); // 设置搜索书籍ID
            $("title").text(title + ' - '+book_title+' · AphpDoc'); // SEO标题
            let markdown = marked.parse(ret.data.markdown);
            $("#author").text(ret.data.author);
            $(".updated").text(ret.data.time_ago);
            $("#page-content").html(markdown); //
            // 按钮链接
            $('a.add-btn').attr('href', $('a.add-btn').attr('data-href')+'?book_id='+ GV.book_id);
            $('a.del-btn').attr('href', "javascript:ajaxConfirm('"+$('a.del-btn').attr('data-href')+'?id='+ GV.doc_id+"','删除[不可恢复]');");
            $('a.act-btn').each(function() {
                $(this).attr('href', $(this).attr('data-href')+'?id='+ GV.doc_id);
            });
            // 上一篇
            if (JSON.stringify(ret.data.prev) !== '[]') {
                $('#prev-link').attr('href', $('#prev-link').attr('data-href')+'?id='+ ret.data.prev.id);
                $('#prev-link').text(ret.data.prev.title);
            } else {
                $('#prev-link').attr('href', '#');
                $('#prev-link').text('没有了');
            }
            // 下一篇
            if (JSON.stringify(ret.data.next) !== '[]') {
                $('#next-link').attr('href', $('#next-link').attr('data-href')+'?id='+ ret.data.next.id);
                $('#next-link').text(ret.data.next.title);
            } else {
                $('#next-link').attr('href', '#');
                $('#next-link').text('没有了');
            }
            if (!without_history) {
                history.pushState({}, title, url);
            }
            //切换右侧菜单激活样式
            active_readed_menu(url);
            NProgress.done();
            // 加亮关键字
            if (wd) {
                let wds = wd.split(","), l = wds.length;
                for (let i = 0; i < l; i++) {
                    $(".markdown-body").highlight(wds[i].trim());
                }
            }
            $('.m-manual .manual-right').animate({scrollTop: 0}, 100);
            // 遍历所有的 code 标签
            $('pre').each(function () {
                // 判断是否具有某个 class 样式，例如 'my-class'
                if (!$(this).hasClass('line-numbers')) {
                    // 如果没有，则添加 class 样式
                    $(this).addClass('line-numbers');
                }
            });
            let prefix = 'language-';
            let regex = new RegExp('\\b' + prefix + '[^ ]*');
            $('pre code').each(function () {
                if (!regex.test($(this).attr('class'))) {
                    $(this).addClass(prefix + 'php'); //prefix + 'php'
                }
            });
            Prism.highlightAll(false);
        } else {
            toast(ret.msg);
            NProgress.done();
        }
    });
}
$(function () {
    // 目录跳转
    $(".article-menu-detail a").click(function (e) {
        e.preventDefault();
        load_doc($(this).attr('href'), '');
    });
    // TOC目录高亮
    $(".manual-right").scroll(function () {
        let top = $(".manual-right").scrollTop();
        if (top > 100) {
            $(".view-backtop").addClass("active");
        } else {
            $(".view-backtop").removeClass("active");
        }
        let headings = document.querySelectorAll('h1, h2, h3, h4, h5, h6');
        let tocLinks = document.querySelectorAll('.markdown-toc-list a');
        let currentHeadingId = '';
        headings.forEach((heading) => {
            const rect = heading.getBoundingClientRect();
            if (rect.top >= 0 && rect.top <= window.innerHeight * 0.5) {
                currentHeadingId = heading.id;
            }
        });
        tocLinks.forEach((link) => {
            if (link.getAttribute('href') === `#${currentHeadingId}`) {
                link.classList.add('active');
            } else {
                link.classList.remove('active');
            }
        });
    });
    // 搜索结果跳转
    $("#searchList").on("click", "a", function () {
        let id = $(this).attr("data-id");
        let url =  GV.base_href + '?id=' + id;
        let _this = $(this);
        _this.parent("li").siblings().find("a").removeClass("active");
        _this.addClass("active");
        load_doc(url, _this.attr("data-wd"));
    });
    // 上下篇
    $(".related-link").on("click","a",function (e) {
        e.preventDefault();
        load_doc($(this).attr("href"),"");
    });
    // 左右方向键，切换上下章节。
    $(document).keydown(function (event) {
        // 如果焦点在文本框，则不切换上下章节
        if($("textarea").is(":focus")){
            return;
        }
        switch (event.keyCode) {
            case 37:
                let href_pre=$(".related-pre a").attr("href");
                if(!$(".related-pre").hasClass("hidden") && href_pre!="#"){
                    load_doc(href_pre,"");
                }
                break;
            case 39:
                let href_next=$(".related-next a").attr("href");
                if(!$(".related-next").hasClass("hidden") && href_next!="#"){
                    load_doc(href_next,"");
                }
                break;
        }
    });
    window.onpopstate=function(e){
        if (location.href.indexOf("#")<0) {
            load_doc(location.pathname,"",true);
        }
    }
    $(".markdown-body").on("click","a",function (e) {
        e.preventDefault();
        var _this = $(this);
        if(_this.find("img").length == 0){
            redirect(_this.attr("href"))
        }
    });
    function redirect(href){
        var hrefLower=href.toLowerCase();
        if(hrefLower.indexOf("http://")==0 || hrefLower.indexOf("https://")==0 ){
            window.open(href);
        }else{
            location.href=href;
        }
    }
    // 图片放大
    $(".markdown-body").on("click", "img",function () {
        var src = $(this).attr("src")
        var nHeight = $(this)[0].naturalHeight
        var nWidth = $(this)[0].naturalWidth
        var winHeight = $(window).height()
        var winWidth = $(window).width()
        var displayWidth = nWidth
        var displayHeight = nHeight
        if(src.toLowerCase().endsWith(".svg")){
            displayWidth = $(this)[0].clientWidth
            displayHeight = $(this)[0].clientHeight
        }
        if (displayWidth>=winWidth*0.95){
            displayWidth = winWidth*0.95
            displayHeight=nHeight*(displayWidth/nWidth)
        }
        console.log(nWidth, nHeight, displayWidth,displayHeight,winWidth,winHeight)
        var style="margin-top: 30px;"
        var bv = $(".photo-viewer")
        var img = bv.find("img")
        if(winHeight>displayHeight){
            var mt = (winHeight - displayHeight - 30 )/2
            if (mt<=30) mt=30
            style="margin-top: " + mt +"px"
        }
        console.log('winheight',winWidth,'displayHeight',displayHeight)
        if(img.length>0){
            img.attr("src", src)
            img.attr("style", style)
        }else {
            bv.append('<img style="'+style+'" src="'+src+'"/>')
        }
        bv.fadeIn();
        $(".photo-viewer").scrollTop(0);
    });
    $(".photo-viewer").click(function () {
        $(this).fadeOut()
    });
    // 加载文档
    load_doc(GV.base_href + '?id=' + GV.doc_id, '');
});